import React, { useImperativeHandle, useMemo, useRef, useState } from 'react';
//@ts-ignore
import '@/pages/components/StyleFile/btnStyle.less';
import { extractFileInfo, Md5_16 } from '@/utils';
import axios from 'axios';
import notify from 'devextreme/ui/notify';
import { useModel } from 'umi';
import './index.less';
import { getCpasByCategory, tbCalculateCpasTable } from './service';

//@ts-ignore

import AddColCompany from '@/pages/FinancialAnalysis/components/addColCompany';
import Formula from '@/pages/FinancialAnalysis/components/formula';
import { FinancialIndicatorsGet, mergeArrays } from '@/pages/FinancialAnalysis/components/server';
import BigNumber from 'bignumber.js';
import { Button, DropDownButton } from 'devextreme-react';
import SaveTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup';
import CpasModal from '~/public/cpas-business/cpas-table/CpasModal';
import CpasTableFs from '~/public/cpas-business/cpas-table/CpasTableFs';
import { CpasIcon } from '~/public/cpas-ui';
import SettingFormPupop from './settingFormPupop';
const AnalysisCpasTableP = React.forwardRef((props: any, ref: any) => {
  const {
    CPASTableProps,
    tableNameGroup,
    excelParams,
    commonCpasTableDisplay,
    CPASTableTabName,
    pageLoading,
  } = props;

  const { tableName, titleName, origin, tabsIndex } = CPASTableProps;
  const { initialState } = useModel('@@initialState');
  const yearDateModel: any = useModel('qjModel');
  const { dataList } = yearDateModel;
  // console.log(yearDateModel, 'yearDateModel');
  let XX = new Date(dataList.at(-1)?.ADateE).getMonth() + 1;
  XX = new BigNumber(12).dividedBy(new BigNumber(XX)).toNumber();
  const { sjnd } = initialState?.curPart;
  const { cpasTableZeroReplace } = initialState?.settings;
  const { dbname, bsdw, zcbfid, zcbfName } = initialState?.curPart;
  const TempleCloumnIndex = 7;
  const cpasTableFsRef = useRef<any>(null);
  const saveTemplatePopupRef = useRef<any>();
  const [showMenuToolBar, setShowMenuToolBar] = useState<boolean>(true);
  // const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const cpasTableTid = useRef<any>(''); // tid
  const refSettingFormPupop = useRef<any>(null);
  const [titleRightText, setTitleRightText] = useState<string>(' ');
  const [titleLeftText, setTitleLeftText] = useState<string>(' ');
  const [titleCenterText, setTitleCenterText] = useState<string>('');
  const [commonCpasTableNot, setCommonCpasTableNot] = useState<string>(' ');
  const [visibleSetting, setvisibleSetting] = useState<boolean>(false);
  const PopupComponentsRef = useRef<any>(null);
  const exportExcelRef = useRef<any>(null);
  const addColCompany = useRef<any>(null);
  const formula = useRef<any>(null);
  const WSS = tableNameGroup?.includes('审定') ? 'SDS' : 'WSS';
  const SDLJFSE = tableNameGroup?.includes('审定') ? 'SDLJFSE' : 'WSLJFSE';
  /**
   *  按钮点击事件
   */

  const onClickformulabutton = () => {
    // const realrealHandSonGridRefRef = getRealCPASTableRef();
    // const data = realrealHandSonGridRefRef.getCpasTableGrid();
    setvisibleSetting(true);
    formula.current?.showPupop([], tableNameGroup);
  };

  /**
   * 点击追加底稿按钮
   */
  const onClickExportToDraft = async () => {
    await cpasTableFsRef?.current?.handsonTableFs?.current?.menuToolRef.current?.exportToDraft();
  };

  // 获取真是的CPASTable的ref
  const getRealCPASTableRef = () => {
    if (cpasTableFsRef.current) {
      const realHandSonGridRef = cpasTableFsRef.current.handsonTableFs.current;
      return realHandSonGridRef;
    }
    return null;
  };

  const buildDataGetTb = async (data: any) => {
    pageLoading(false, '获取计算数据中...');
    let cell_formula_result: any = await tbCalculateCpasTable({
      formulas: data,
      dbname: dbname,
    });
    pageLoading(true, '获取计算数据完成');
    //{cell_2_2:{value:"22"},cell_2_3:{value:"23"}}
    if (cell_formula_result?.data?.errors.length) {
      notify('取数接口计算错误', 'error', 2000);
    }
    return cell_formula_result?.data?.data;
  };

  let cellCumputer = (cell_1: any, cell_2: any) => {
    let arr: any[] = [];
    let cell3: any = new BigNumber(cell_2);
    let cell1 = new BigNumber(cell_1);

    cell3 = new BigNumber(cell3).minus(cell1);

    arr.push(cell3.toFixed(4));
    arr[1] = cell3.absoluteValue().gte(0.5) ? '显著' : cell3.absoluteValue().gte(0.2) ? '关注' : '';
    return arr;
  };
  let buildDataSetData = (data: any, cell_formula_result: any) => {
    try {
      data.forEach((a: any) => {
        const isAuto = JSON.parse(a[a.length - 1])?.formula;
        if (isAuto > '') {
          let rid = JSON.parse(a[a.length - 1]).rId;
          let cell_1 = cell_formula_result[`cell_${rid}_2`]
            ? cell_formula_result[`cell_${rid}_2`]?.value
            : null;
          let cell_2 = cell_formula_result[`cell_${rid}_3`]
            ? cell_formula_result[`cell_${rid}_3`]?.value
            : null;
          // row =row.concat([cell_1,cell_2])
          a[2] = cell_1 ? new BigNumber(cell_1).toFixed(4) : null;
          a[3] = cell_2 ? new BigNumber(cell_2).toFixed(4) : null;
          if (cell_1 && cell_2) {
            let d = cellCumputer(a[2], a[3]);

            a[4] = d[0];
            a[5] = d[1];
          } else {
            a[4] = 0;
            a[5] = '';
          }

          return a;
        }
      });
      return data;
    } catch (error) {
      console.log(error);
      return [];
    }
  };

  const reCpu = async () => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      let data = realrealHandSonGridRefRef.getCpasTableGrid(); // 获取的数不对
      let cell_formula = buildFiled(data.data);
      const result_tb = await buildDataGetTb(cell_formula);
      if (result_tb) {
        const redata = buildDataSetData(data.data, result_tb);
        data.data = redata;
        await realrealHandSonGridRefRef.reloadTable(data, 'fs', null, true);
      }
    }
  };

  /**
   *
   * @param serverName 初次获取
   * @param isRead
   * @returns
   */
  const loadTableByServerData = async (serverName: string, isRead = false) => {
    let serverData: any;
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      console.log('@@@ 获取真是的CPASTable的ref', realrealHandSonGridRefRef);
      try {
        serverData = await realrealHandSonGridRefRef.loadTableByServer(serverName);
        console.log('--------serverData初始数据 @@@', serverData);
        if (serverData.data) {
          cpasTableTid.current = serverData.tid;

          // 处理项目浮框显示问题
          const d = await FinancialIndicatorsGet({ dbName: dbname });
          const arr1 = d.data?.filter(
            (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
              a.type === '1',
          );
          serverData.cellsMeta = serverData.cellsMeta.map((b: any) => {
            if (b?.comment?.id) {
              let arr = arr1.filter(
                (a: { IndicatorID: string }) => a.IndicatorID === b?.comment?.id,
              );
              if (arr.length) {
                return {
                  ...b,
                  comment: {
                    ...b?.comment,
                    value: `${arr[0].CalculationFormula}\n ${
                      arr[0].IndicatorAnalysisTips ? arr[0].IndicatorAnalysisTips : ''
                    }`,
                  },
                };
              } else {
                return b;
              }
            } else {
              return b;
            }
          });
          await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
          notify(`获取该表数据成功！`, 'success', 2000);
          return {
            data: serverData,
            msg: serverData.msg,
            success: true,
          };
        } else {
          // setServerDataLen(2);
          notify(`获取数据失败：${serverData.msg}！`, 'warning', 2000);
          return {
            data: [],
            msg: serverData.msg,
            success: false,
          };
        }
      } catch (e) {
        console.log(e);
        notify(`没有该表:【${serverName}】的数据！`, 'warning', 2000);

        realrealHandSonGridRefRef.resetTable('fs');
        return {
          data: [],
          msg: `没有该表:【${serverName}】的数据！`,
          success: false,
        };
      }
    }
    return;
  };

  /**
   * cpas表格数据存储到线上
   */
  const saveToServerByCpasData = async (data?: any) => {
    const realHandSonGridRef = getRealCPASTableRef();
    if (realHandSonGridRef) {
      try {
        const tid = Md5_16(tableName);
        if (!data) {
          data = realHandSonGridRef.getCpasTableGrid(); //  获取表格数据
        }

        let newCellMeta: any = [];
        data.cellsMeta.forEach((a: any) => {
          if (a?.comment?.value) {
            newCellMeta.push({ ...a, comment: { ...a.comment, value: '' } });
          } else {
            newCellMeta.push(a);
          }
          //   if (countChineseCharacters(a?.comment?.value) > 160) {
          //     let str = a?.comment?.value.split('指标分析提示：');
          //     if (str.length === 2) {
          //       str = [1];
          //     } else {
          //       str = str;
          //     }
          //     newCellMeta.push({ ...a, comment: { value: str, readOnly: true } });
          //   } else {
          //     newCellMeta.push(a);
          //   }
          // } else {
          //   newCellMeta.push(a);
          // }
        });
        data.cellsMeta = newCellMeta;
        const res = await realHandSonGridRef.saveToServerByCpasData(data, tableName, 'fs', tid, '');
        if (res) {
          notify(`保存成功！`, 'success', 2000);
          return true;
        }
        return false;
      } catch (error) {
        console.log(error);
        notify(`保存失败！`, 'error', 2000);
        return false;
      }
    }
    return false;
  };

  const exportExcel = async (isAll: boolean) => {
    // console.log('@@@', excelParamsData);
    // let tempSignData: any[] = await getDevDataList();
    let tempExcelDataArr: any = [...excelParams];

    const tempExcelData = tempExcelDataArr.map((itemParam: any, index: number) => {
      itemParam.tableDate = ' ';
      itemParam.signDirection = 'vertical';
      return itemParam;
    });
    let xlsxName = ' ';
    if (origin === '审定财务') {
      // XXXX公司XXXX年度未审报表趋势分析.xlsx
      xlsxName = `${bsdw}${sjnd}年度审定报表比率分析`;
    } else {
      xlsxName = `${bsdw}${sjnd}年度未审报表比率分析`;
    }

    // console.log(tempExcelData, '@@@');
    // 1、单个导出文件名称：未审财务报表+功能页签名，审定财务报表+功能页签名，试算平衡表：年度—试算平衡表—页签名—期初/期末；
    // 2、批量导出：未审财务报表、审定财务报表、年度—试算平衡表；
    //@ts-ignore
    const dialog_result = await window.electronComponents?.showSaveDialog(
      'xlsx',
      `${xlsxName}.xlsx`,
    );
    if (!dialog_result.canceled) {
      let radioTable: any = [];
      if (isAll) {
        radioTable = tempExcelData.filter((item: any) => {
          return item.isBatchExport;
        });
      } else {
        radioTable = tempExcelData.filter((item: any) => {
          return item.cpastableParam.tname === tableName;
        });
      }
      // console.log(tempExcelData, radioTable, tableName, '@@@');
      const fileData = extractFileInfo(dialog_result.filePath);
      const params = {
        excelInfo: radioTable,
        dbname,
        directoryPath: fileData.dirName,
        excelFileName: fileData.fileName,
        projectName: bsdw,
      };
      const url = `/cpasApi/cpasTableEngine/getCpatableToBatchExportExcel`;
      const data = await axios.post(url, params);
      if (data.data?.data?.code) {
        return {
          code: data.data.data.code,
          msg: data.data.data.msg,
          ok: data.data.data.ok,
          type: '导出',
        };
      }
      const tempMsg = 'EBUSY: resource busy or locked, open';
      const isTrue = data.data.msg.includes(tempMsg);
      if (isTrue) {
        return {
          code: data.data.code,
          msg: '文件已被程序打开，需要关闭已被打开的文件。',
          ok: data.data.ok,
          type: '导出',
        };
      }
      return {
        code: data.data.code,
        msg: data.data.msg,
        ok: data.data.data,
        type: '导出',
      };
    }
    return {
      code: 404,
      msg: '取消了选择路径！',
      ok: false,
      type: '取消',
    };
  };

  const batchExport = async (isTemp: boolean) => {
    pageLoading(false, '导出中...');

    const res = await exportExcel(isTemp);
    pageLoading(true, '导出完成...');
    if (res.type === '导出') {
      if (res.ok) {
        notify(`导出成功！`, 'success', 2000);
      } else {
        PopupComponentsRef.current.show({
          title: '提示信息',
          content: res.msg,
          cancelText: '取消',
          okText: '确定',
          okCallback: () => {
            PopupComponentsRef.current.closeDia();
          },
        });
      }
    }
  };

  const getHeaderData = async (curtid: string) => {
    console.log(curtid, '@@@');
    //
    // if (!curtid) return;
    if (origin === '审定财务') {
      let tempHeader: any = {};
      let tempAlias: any = {};
      const resAlias = await getCpasByCategory({
        dbname,
        tid: [curtid],
        category: 'aliasName',
      });
      if (resAlias.data.length) {
        tempAlias = JSON.parse(resAlias.data[0].describe);
        setTitleCenterText(tempAlias?.headerTitleText ?? '');
      } else {
        setTitleCenterText('');
      }
      const resHeader = await getCpasByCategory({
        dbname,
        tid: [curtid],
        category: 'fsHeader',
      });
      if (resHeader.data.length) {
        tempHeader = JSON.parse(resHeader.data[0].describe);
        if (tempHeader?.hasOwnProperty('headerTitleLeftText')) {
          let leftText = tempHeader.headerTitleLeftText
            ? `${tempHeader.headerTitleLeftText}${bsdw}`
            : ' ';
          setTitleLeftText(leftText);
        }

        if (tempHeader?.hasOwnProperty('headerTitleRightText')) {
          setTitleRightText(tempHeader?.headerTitleRightText ?? ' ');
        } else {
          if (tempHeader) {
            setTitleRightText(tempHeader);
            setTitleLeftText(`编制单位: ${bsdw}`);
          } else {
            setTitleRightText(' ');
            setTitleLeftText(' ');
          }
        }
      } else {
        setTitleLeftText(' ');
        setTitleRightText(' ');
      }
    }
  };

  const onClickAddCompany = () => {
    // 获取列
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    const data = realrealHandSonGridRefRef.getCpasTableGrid();

    const arr = data.header.slice(7, data.header.length - 1); // 获取公司列
    realrealHandSonGridRefRef.hot.deselectCell();
    // 添加列
    //
    addColCompany.current.showPupop(
      arr.map((a: any) => {
        return { name: a.label, id: a.key };
      }),
    );
  };

  const onClickCompanyDeletecallback = async (name: any) => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    let data = realrealHandSonGridRefRef.getCpasTableGrid();
    // 存在符合表头
    let cindex = 6; // 偏移值
    data.header = data.header.filter((a: any, index: number) => {
      if (a.label === name) {
        data.data = data.data.map((a: any) => {
          a.splice(index + cindex, 1);
          return a;
        });
        return false;
      } else {
        return true;
      }
    });

    await realrealHandSonGridRefRef.reloadTable(data, 'fs', null, true);
  };

  const buildFiled = (arr: any[]) => {
    let cell_formula = {};
    arr.forEach((a: any, index: number) => {
      if (index > 0 && JSON.parse(a[a.length - 1]).formula > '') {
        let rid = JSON.parse(a[a.length - 1]).rId;
        cell_formula[`cell_${rid}_2`] = replaceCell(JSON.parse(a[a.length - 1]).formula).formula_3;
        cell_formula[`cell_${rid}_3`] = replaceCell(JSON.parse(a[a.length - 1]).formula).formula_2;
      }
    });
    return cell_formula;
  };

  /**
   * 核心函数又一条系统公式，生成带年度的公式，垮期间公式和已审未审的公式
   * @param CalculationFormulaSystem
   * @returns
   */
  const replaceCell = (CalculationFormulaSystem: any) => {
    // 1，未审需要替换，本期审定，替换为未审,未审还是为审
    const replaceOneYearFor = (f: string) => {
      // return f.replaceAll()
      // 存在垮区间替换 不用替换，不存在垮区间，直接替换为都是期末
      if (f.includes('期初') || f.includes('上期')) {
        return f;
      } else {
        if (!(f.includes('期末') || f.includes('本期'))) {
          return f
            ?.replaceAll('资产表', '资产表_期末')
            ?.replaceAll('负债表', '负债表_期末')
            ?.replaceAll('利润表', '利润表_本期');
        } else {
          // 不对的公式
          return f;
        }
      }
    };

    let formula_2 = CalculationFormulaSystem?.replaceAll('{sjnd}', sjnd);

    formula_2 = replaceOneYearFor(formula_2);

    formula_2 = formula_2
      ?.replaceAll('X', XX)
      ?.replaceAll('SDS', WSS)
      ?.replaceAll('SDLJFSE', SDLJFSE)
      ?.replaceAll('WSS', WSS)
      ?.replaceAll('WSLJFSE', SDLJFSE);

    // 原始公式要区分期末和期初
    let formula_3 = CalculationFormulaSystem?.replaceAll('{sjnd}', Number(sjnd - 1));
    formula_3 = replaceOneYearFor(formula_3);
    //   ?.replaceAll('资产表', '资产表_期末')
    //   ?.replaceAll('负债表', '负债表_期末')
    //   ?.replaceAll('利润表', '利润表_本期');
    formula_3 = formula_3
      ?.replaceAll('X', XX)
      ?.replaceAll('SDS', WSS)
      ?.replaceAll('SDLJFSE', SDLJFSE)
      ?.replaceAll('WSS', WSS)
      ?.replaceAll('WSLJFSE', SDLJFSE);

    return { formula_2: formula_2, formula_3: formula_3 };
  };
  const onClickAddItemOKcallback = async (arr: any[]) => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    const data = realrealHandSonGridRefRef.getCpasTableGrid();
    // 获取到所有的项目列构建
    // 同时请求数据接口
    let tmp: any = [];
    let cellsMeta: any[] = [];
    let cell_formula = {};
    //data.cellsMeta.filter((a:any)=>a.col ===1 && a.comment)
    arr.forEach((i: any, index: number) => {
      if (
        i.TaskIndicatorID_Parent_ID !== '0' &&
        i.CalculationFormulaSystem &&
        i.CalculationFormulaSystem !== ''
      ) {
        cell_formula[`cell_${i.IndicatorID}_2`] = replaceCell(i.CalculationFormulaSystem).formula_3;
        cell_formula[`cell_${i.IndicatorID}_3`] = replaceCell(i.CalculationFormulaSystem).formula_2;
      }
      // let formula=i.comment.value.split('\n')[0]
    });

    let cell_formula_result: any = await buildDataGetTb(cell_formula);

    arr.forEach((a: any, index: number) => {
      let row = [
        `${a.IndicatorName}`,
        a.TaskIndicatorID_Parent_ID !== '0' ? a.IndicatorName : `${a.IndicatorName}:`,
      ];

      if (a.TaskIndicatorID_Parent_ID !== '0') {
        let olddata = data.data.filter((c: any[]) => c.toString().includes(a.IndicatorName)); //保存之前的项目 有相同的项目名字，存原因分析和公司列
        if (olddata.length === 1) {
          // 处理子节点
          // 如果是二次更新，自动的重新计算，手动的保存之前的
          if (a.ManualOrAutomatic === '自动') {
            let cell_1 = null;
            let cell_2 = null;
            if (cell_formula_result[`cell_${a.IndicatorID}_2`]?.value) {
              cell_1 = new BigNumber(cell_formula_result[`cell_${a.IndicatorID}_2`]?.value).toFixed(
                4,
              );
            }
            if (cell_formula_result[`cell_${a.IndicatorID}_3`]?.value) {
              cell_2 = (cell_formula_result[`cell_${a.IndicatorID}_3`]?.value).toFixed(4);
            }

            row = row.concat([cell_1, cell_2]);
            if (cell_1 && cell_2) {
              let cell = cellCumputer(cell_1, cell_2);
              row.push(cell[0]);
              row.push(cell[1]);
            } else {
              row = row.concat([null, null]);
            }
          } else if (a.ManualOrAutomatic === '手动') {
            // 如果是上次上手输入的不能被清空
            [2, 3].forEach((d: any) => {
              row.push(olddata[0][d]);
            });
            row = row.concat([
              `=IFERROR(D${index + 2}-C${index + 2},0)`,
              `=IF(ABS(E${index + 2})>=0.5, "显著", IF( ABS(E${index + 2})>=0.2, "关注", ""))`,
            ]);
          } else {
            row = row.concat([
              null,
              null,
              `=IFERROR(D${index + 2}-C${index + 2},0)`,
              `=IF(ABS(E${index + 2})>=0.5, "显著", IF(ABS(E${index + 2})>=0.2, "关注", ""))`,
            ]);
          }
          // 不管自动手动都是之前保存的
          data.header
            .filter((d: any) => d.key.startsWith('company_') || d.label.includes('原因'))
            .forEach((x: any, index: number) => {
              row.push(olddata[0][6 + index]);
            });
        } else {
          // 如果是首次
          if (a.ManualOrAutomatic === '自动') {
            let cell_1 = cell_formula_result[`cell_${a.IndicatorID}_2`]
              ? cell_formula_result[`cell_${a.IndicatorID}_2`]?.value
              : null;
            let cell_2 = cell_formula_result[`cell_${a.IndicatorID}_3`]
              ? cell_formula_result[`cell_${a.IndicatorID}_3`]?.value
              : null;
            cell_1 = cell_1 ? new BigNumber(cell_1).toFixed(4) : null;
            cell_2 = cell_2 ? new BigNumber(cell_2).toFixed(4) : null;
            row = row.concat([cell_1, cell_2]);
            if (cell_1 && cell_2) {
              let cell = cellCumputer(cell_1, cell_2);
              row.push(cell[0]);
              row.push(cell[1]);
            } else {
              row = row.concat([null, null]);
            }
          } else {
            row = row.concat([
              null,
              null,
              `=IFERROR(D${index + 2}-C${index + 2},0)`,
              `=IF(ABS(E${index + 2})>=0.5, "显著", IF(ABS(E${index + 2})>=0.2, "关注", ""))`,
            ]);
          }
          row = row.concat([null]); // 原因
          data.header
            .filter((d: any) => d.key.startsWith('company_'))
            .forEach((x: any) => {
              row.push(null);
            });
        }
      } else {
        // 处理父节点
        row = row.concat([null, null, null, null, null]); // 数字+原因分析
        data.header
          .filter((d: any) => d.key.startsWith('company_'))
          .forEach((x: any) => {
            row.push(null);
          });
      }
      let row_formula = `${
        a.ManualOrAutomatic === '自动' && a.CalculationFormulaSystem
          ? a.CalculationFormulaSystem
          : ''
      }`;
      row.push(JSON.stringify({ rId: a.IndicatorID, formula: row_formula }));
      if (a.ManualOrAutomatic === '自动') {
        [2, 3, 4, 5].forEach((d: any) => {
          cellsMeta.push({
            col: d,
            readOnly: true,
            row: index + 1,
            // custom: {className:'htDimmed'},
          });
        });
      } else {
        if (a.TaskIndicatorID_Parent_ID !== '0') {
          // 按行处理，手动，包含父级节点
          [4, 5].forEach((d: any) => {
            cellsMeta.push({
              col: d,
              readOnly: true,
              row: index + 1,
              // custom: {className:'htDimmed'},
            });
          });
        } else {
          [2, 3, 4, 5].forEach((d: any) => {
            cellsMeta.push({
              col: d,
              readOnly: true,
              row: index + 1,
              // custom: {className:'htDimmed'},
            });
          });
        }
      }
      if (a.TaskIndicatorID_Parent_ID !== '0') {
        cellsMeta.push({
          col: 1,
          custom: { ht: null, bl: 1, r: { type: 1, val: 2 } },
          comment: {
            id: a.IndicatorID,
            value: `${a.CalculationFormula}\n ${
              a.IndicatorAnalysisTips ? a.IndicatorAnalysisTips : ''
            }`,
            readOnly: true,
          },
          row: index + 1,
          readOnly: true,
        });
      } else {
        cellsMeta.push({
          col: 1,
          custom: { bl: 2 },
          row: index + 1,
          readOnly: true,
        });
      }

      tmp.push(row);
    });

    data.data = [data.data[0]].concat(tmp);
    data.cellsMeta = cellsMeta;
    await realrealHandSonGridRefRef.reloadTable(data, 'fs', null, true);
    let newCellMeta: any = [];
    const countChineseCharacters = (str: string) => {
      // 使用正则表达式匹配所有汉字字符
      const regex = /[\u4e00-\u9fa5]/g;
      // 执行匹配，返回匹配结果的数组
      const matches = str.match(regex);
      // 返回匹配到的汉字数量
      return matches ? matches.length : 0;
    };
    cellsMeta.forEach((a: any) => {
      if (a?.comment?.value) {
        newCellMeta.push({ ...a, comment: { ...a?.comment, value: '' } });
      } else {
        newCellMeta.push(a);
      }
      //   if (countChineseCharacters(a?.comment?.value) > 160) {
      //     let str = a?.comment?.value.split('指标分析提示：');
      //     if (str.length === 2) {
      //       str = [1];
      //     } else {
      //       str = str;
      //     }
      //     newCellMeta.push({ ...a, comment: { value: str, readOnly: true } });
      //   } else {
      //     newCellMeta.push(a);
      //   }
      // } else {
      //   newCellMeta.push(a);
      // }
    });
    data.cellsMeta = newCellMeta;
    await saveToServerByCpasData(data);
  };
  const onClickAddCompanyOKcallback = async (arr: any[], deleteArr: any[]) => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    const data = realrealHandSonGridRefRef.getCpasTableGrid();
    // data.header.push(})
    // 先处理删除的
    if (arr.length == 0) {
      data.data = data.data.map((a: any) => {
        a.splice(TempleCloumnIndex, data.header.length - 1 - TempleCloumnIndex);
        return a;
      });
      data.header = data.header.filter((a: any) => !a.key.startsWith('company_'));
    } else {
      if (deleteArr.length) {
        let index = 0;
        deleteArr.forEach((a: any) => {
          data.header = data.header.filter((e: any, i: any) => {
            if (e.label !== a) {
              return true;
            } else {
              index = i;
              return false;
            }
          });
        });
        data.data = data.data.map((a: any) => {
          a.splice(index, 1);
          return a;
        });
      }
    }
    // 在处理新增和位置变的，TempleCloumnIndex:7写死的值随模版的列变化
    arr.forEach((a: any, index: number) => {
      if (data.header[index + TempleCloumnIndex].label !== a.data.name) {
        let col = {
          label: a.data.name,
          key: `company_${a.key}`,
          config: { width: 150, type: 'text' },
        };
        data.header.splice(-1, 0, col); //倒数第二位置新增

        data.data = data.data.map((a: any) => {
          a.splice(-1, 0, null);
          return a;
        });
      }
    });
    await realrealHandSonGridRefRef.reloadTable(data, 'fs', null, true);
    const resSave = await saveToServerByCpasData();

    //await  cpasTableFsRef?.current?.handsonTableFs?.current?.menuToolRef.current?.insertColumnHandle({itemData:{id:1}},true)
  };

  useImperativeHandle(ref, () => ({
    CPASInit2: async (rundata: string, isBatch: boolean) => {
      await loadTableByServerData(rundata);
      await getHeaderData(cpasTableTid.current);
    },
    reCumputer: async (params: any) => {
      const d = await FinancialIndicatorsGet({ dbName: dbname });
      // await reCpu();
      const arr1 = d.data?.filter(
        (a: { from_type: string; TaskIndicatorID_Parent_ID: string; type: string }) =>
          a.from_type?.includes('传统行业指标（常用）') && a.type === '1',
      );

      await onClickAddItemOKcallback(mergeArrays(arr1, []));
    },

    saveToServer: async (params: any) => {
      await saveToServerByCpasData();
    },
  }));

  return (
    <div className="commonCpasTableTB">
      <div className="btnsTools">
        <Button
          type="default"
          className="defaultBtn"
          onClick={async () => {
            await reCpu();
          }}
          text="重算"
        />
        <Button
          type="default"
          className="defaultBtn"
          onClick={async () => {
            await saveToServerByCpasData();
          }}
          text="保存"
        />
        <Button className="defaultBtn" onClick={onClickformulabutton} text="指标库" />
        <Button className="defaultBtn" onClick={onClickAddCompany} text="添加同行公司" />
        {/* <Button
          className="defaultBtnWhite purpleBtnUI"
          onClick={() => {
            setShowMenuToolBar(!showMenuToolBar);
          }}
          text="模板设计"
        /> */}
        <DropDownButton
          style={{ height: '30px', margin: '0px 8px 0 4px' }}
          text={origin === '审定财务' ? '导出' : '导出导入'}
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '导出到Excel文件') {
              batchExport(e.itemData === '批量导出报表');
            } else if (e.itemData === '追加到Excel底稿') {
              await onClickExportToDraft();
            } else if (e.itemData === '导出设置') {
              //   setVisibleSetting(true);
              refSettingFormPupop.current?.showPupop(
                {
                  capsTid: cpasTableTid.current,
                  capsOrigin: origin,
                  capsTabName: CPASTableTabName,
                  capsTitleName: titleCenterText,
                  capsTitleDate: '',
                },
                {
                  okCallback: async () => {
                    // setVisibleSetting(false);
                    await getHeaderData(cpasTableTid.current);
                  },
                  cancelCallback: () => {
                    // setVisibleSetting(false);
                  },
                },
              );
            }
          }}
          items={['导出到Excel文件', '追加到Excel底稿']}
        />
        {/* <DropDownButton
          style={{ height: '30px', marginRight: '4px' }}
          text="模板"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '切换模板') {
            } else {
              saveTemplatePopupRef.current.showTemplate();
            }
          }}
          items={['切换模板', '保存模板']}
        /> */}
        <div className="boxRight" />
        <Button
          className="defaultReloadBtnWhite"
          render={() => <CpasIcon type="icon-refresh" fontSize={16} />}
          onClick={async () => {
            await loadTableByServerData(tableName);
            await getHeaderData(cpasTableTid.current);
          }}
        />
      </div>
      <div className={`commonCpasTable ${commonCpasTableDisplay}  ${commonCpasTableNot} `}>
        <CpasTableFs
          tabGroup="fs-tab"
          tabLevel={2}
          ieType="json,draft"
          numberZeroReplace={cpasTableZeroReplace}
          type={'fs'}
          name={tableName}
          isShowMenuToolBar={showMenuToolBar}
          // verifyMode={fa}
          notes={{ tid: cpasTableTid.current }}
          tableDate={''}
          tableTitle={titleCenterText}
          tableRiDesc={titleRightText}
          tableLfDesc={titleLeftText}
          // isTest={true}
          ref={cpasTableFsRef}
          draftSheetName={titleName}
        />
      </div>
      {/* <CpasTableChangePupop ref={cpasTableChangePupopRef} tableSaveAndReload={saveAndReload} /> */}
      <SaveTemplatePopup
        ref={saveTemplatePopupRef}
        okCallback={async (data: any) => {
          console.log(data, '@@@ 保存模板');
          const res: any = await saveTemplateApi({
            dbName: dbname,
            templateName: data,
            type: 'fs',
            tableNames: [tableNameGroup],
          });
          if (res.success) {
            notify('保存成功', 'success', 2000);
          } else {
            notify('保存失败', 'error', 2000);
          }
        }}
        cancelCallback={() => {
          console.log('@@@ ， 取消');
        }}
      />
      {/* <PopupComponents ref={PopupComponentsRef} /> */}
      <SettingFormPupop ref={refSettingFormPupop} />
      {useMemo(() => {
        return <Formula ref={formula} AddItemOKcallback={onClickAddItemOKcallback} />;
      }, [visibleSetting])}

      <AddColCompany
        ref={addColCompany}
        addCompanyCol={onClickAddCompanyOKcallback}
        CompanyDelete={onClickCompanyDeletecallback}
      />
      <CpasModal
        ref={exportExcelRef}
        type="fs"
        zcbfid={zcbfid}
        zcbfName={zcbfName}
        exportSort={['资产表', '负债表', '利润表', '现金流量表', '现金流补充资料表']}
      />
      {/* <ImportExcelModal ref={importExcelRef} type="fs" title="导入Excel报表" okCallback={async () => { await loadTableByServerData(tableName); }} /> */}
    </div>
  );
});
export default React.memo(AnalysisCpasTableP);
